import axios from "axios";
import React, { useEffect, useState } from "react";
import {
  Table,
  Button,
  Space,
  Popconfirm,
  Modal,
  Form,
  Input,
  message as antdMessage,
  Row,
  Col,
  Divider,
  InputNumber,
} from "antd";
import { useLocation, useSearchParams } from "react-router-dom";
interface ListState {
  id: string;
  image: string;
  title: string;
  word: string;
  price: number;
}

const Index: React.FC = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  const keyword = searchParams.get("keyword") || "";
  const location = useLocation();
  // 数据
  const [list, setList] = useState<ListState[]>([]);
  const [min, setMin] = useState(searchParams.get('min') || 0);
  const [max, setMax] = useState(searchParams.get('max') || 0);
  // 列表列数据
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "描述",
      dataIndex: "word",
      key: "word",
    },
    {
      title: "图片",
      dataIndex: "image",
      key: "image",
      // 自定义渲染
      render(text: string) {
        return <img src={text} alt="" height={40} />;
      },
    },
    {
      title: "单价",
      dataIndex: "price",
      key: "price",
    },
    {
      title: (
        <Button type="primary" danger>
          批量删除
        </Button>
      ),
      dataIndex: "id",
      key: "id",
      render(text: string, record: ListState) {
        return (
          <Space>
            <Button type="primary" onClick={() => openModal(record)}>
              编辑
            </Button>
            <Popconfirm
              title="警告"
              description="确定要删除吗?"
              onConfirm={() => deleteListByID(text)}
              okText="确定"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                // onClick={() => deleteListByID(text)}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  // 请求数据函数
  const fetchList = async () => {
    const resp = await axios.get("/api/list", { params: { keyword, min, max } });
    setList(resp.data.data);
  };
  // 删除数据函数--通过id
  const deleteListByID = async (id: string) => {
    const resp = await axios.delete("/api/list", { params: { id } });
    fetchList();
  };

  // 副作用函数
  useEffect(() => {
    // 请求数据
    fetchList();
  }, [location]);

  // 弹框操作
  const [isOpen, setIsOpen] = useState(false);
  // 当前编辑的数据行
  const [rowItem, setRowItem] = useState<ListState>({} as ListState);
  const [form] = Form.useForm();
  const openModal = (row: ListState) => {
    setIsOpen(true);
    setRowItem(row);
  };

  const handleOK = async () => {
    setIsOpen(false);
    // 获取表单数据
    const values = form.getFieldsValue(true);
    // 发送数据修改请求
    const resp = await axios.post("/api/list/update", values);
    antdMessage.success(resp.data.message);
    fetchList();
  };

  const onPressEnter = (value: string) => {
    setSearchParams({
      keyword: value,
      min: min.toString(),
      max: max.toString(),
    });
  };
  const queryPrice = () => {
    setSearchParams({ min: min.toString(), max: max.toString(), keyword });
  };

  return (
    <div>
      <Row style={{ alignItems: "center" }}>
        <Col span={1}>搜索：</Col>
        <Col span={22}>
          <Input
            defaultValue={keyword}
            onPressEnter={(e) =>
              onPressEnter((e.target as HTMLInputElement).value)
            }
          ></Input>
        </Col>
      </Row>
      <Row style={{ alignItems: "center" }}>
        <Col span={2}>价格区间：</Col>
        <Col span={4}>
          <InputNumber
            style={{ width: "100%" }}
            value={min}
            onChange={(value) => value && setMin(value)}
          ></InputNumber>
        </Col>
        <Col span={2}>
          <Divider></Divider>
        </Col>
        <Col span={4}>
          <InputNumber
            style={{ width: "100%" }}
            value={max}
            onChange={(value) => value && setMax(value)}
          ></InputNumber>
        </Col>
        <Col span={2}>
          <Button type="primary" onClick={queryPrice}>
            查询
          </Button>
        </Col>
      </Row>
      <Table
        rowSelection={{
          onChange(keys) {
            console.log(keys);
          },
        }}
        dataSource={list}
        columns={columns}
        rowKey="id"
      ></Table>
      <Modal
        title="编辑"
        open={isOpen}
        okText="确定"
        cancelText="取消"
        onCancel={() => setIsOpen(false)}
        onOk={() => handleOK()}
        destroyOnClose
      >
        <Form
          form={form}
          preserve={false}
          wrapperCol={{ span: 22 }}
          labelCol={{ span: 2 }}
          initialValues={rowItem}
        >
          <Form.Item label="id" name="id">
            <Input disabled></Input>
          </Form.Item>
          <Form.Item label="标题" name="title">
            <Input></Input>
          </Form.Item>
          <Form.Item label="描述" name="word">
            <Input></Input>
          </Form.Item>
          <Form.Item label="图片" name="image">
            <Input></Input>
          </Form.Item>
          <Form.Item label="单价" name="price">
            <Input></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Index;
